﻿using System;
using System.CodeDom;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Reflection;
using Zinnia.Lite.Driver;
using Zinnia.Lite.Exceptions;
using Zinnia.Lite.Untilty;

namespace Zinnia.Lite.Configs
{
    /// <summary>
    /// 数据库连接配置
    /// </summary>
    public class DbConfigs
    {
        public DbConfigs(string storageXmlConfigs)
        {
            var storageconfigs = XMLHelper.XmlDeserialize<StorageConfigs>(storageXmlConfigs);
            Configs = new ConcurrentDictionary<string, DbConfig>();
            if (storageconfigs.StorageConfig.Any())
                foreach (var config in storageconfigs.StorageConfig)
                    Configs.Add(config.StorageName, GetDbConfig(config));
        }

        public DbConfig GetDbConfig(StorageConfig config)
        {
            var driver = config.DbDriver.Split(',');
            var assembly = Assembly.Load(driver[0]);
            var driverType = assembly.GetType(driver[1], true, true);
            return new DbConfig
            {
                DbConfigName = config.StorageName,
                DbConn = ((IDriver)Activator.CreateInstance(driverType)).GetDbConnection(config),
                DbModel = null
            };
        }

        public IDictionary<string, DbConfig> Configs { get; set; }

        public DbConfig GetDbConfig(string dbConfigName)
        {
            if (!Configs.Any()) throw new LiteException("未找到StorageConfigs配置信息");
            return Configs[string.IsNullOrWhiteSpace(dbConfigName) ? "Current" : dbConfigName];
        }
    }
    /// <summary>
    /// 数据库配置
    /// </summary>
    public class DbConfig
    {
        /// <summary>
        /// 连接配置名称【多数据库连接时有用】
        /// </summary>
        public string DbConfigName { get; set; }
        /// <summary>
        /// 数据库连接
        /// </summary>
        public DbConnection DbConn { get; set; }
        /// <summary>
        /// 数据库约定(多数据支持)
        /// </summary>
        public DbCompiledModel DbModel { get; set; }
        /// <summary>
        /// DbcontextOwnsConnection 是false,则释放上下文时将不会释放该连接
        /// </summary>
        public bool DbcontextOwnsConnection { get; set; }
    }
}
